import { useState, useRef, useEffect, useCallback } from 'react';
import { Box,Button,TextField,Stack, FormControl, InputLabel, Select, MenuItem, CircularProgress,Typography } from '@mui/material';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Cancel';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker';
import { bookingService, roomService, authService } from '../../services';
import { useMessage } from '../../hooks';

const CreateBooking = () => {
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    roomId: '',
    start: dayjs().add(30, 'minute'), 
    end: dayjs().add(1.5, 'hour')
  });
  const [rooms, setRooms] = useState([]);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});
  
  const titleRef = useRef(null);
  const navigate = useNavigate();
  const { showSuccess, showError } = useMessage();
 
  const fetchRooms = useCallback(async () => {
    try {
      setLoading(true);
      const response = await roomService.getRooms(0, 100);
      setRooms(response?.items || []);
    } catch (err) {
      showError('Failed to load rooms');
    } finally {
      setLoading(false);
    }
  }, [showError]);

  useEffect(() => {
    fetchRooms();
  }, [fetchRooms]);
 
  const validateForm = () => {
    const newErrors = {};
    if (!formData.title) newErrors.title = 'Title is required';
    if (!formData.roomId) newErrors.roomId = 'Room is required';
    if (!formData.start) newErrors.start = 'Start time is required';
    if (!formData.end) newErrors.end = 'End time is required';
    if (formData.start && formData.end && formData.start.isAfter(formData.end)) {
      newErrors.end = 'End time must be after start time';
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  
  const onSaveBooking = async (e) => {
    e.preventDefault();
    if (!validateForm()) return;

    setLoading(true);
    const bookingData = {
      StartDate: formData.start,
      EndDate: formData.end,
      RoomId: formData.roomId,
      UserId: authService.getUser().userId,
      Title: formData.title,
      Description: formData.description,
    };

    try {
      await bookingService.createBooking(bookingData);
      showSuccess('Booking created successfully');
      navigate("/bookings");
    } catch (err) {
      showError(err || 'Failed to create booking');
    } finally {
      setLoading(false);
    }
  };

  const onPropertyChange = (field) => (e) => {
    setFormData(prev => ({
      ...prev,
      [field]: e.target ? e.target.value : e
    }));
    setErrors(prev => ({ ...prev, [field]: '' }));
  };

  if (loading && rooms.length === 0) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box 
      sx={{ 
        maxWidth: 600, 
        mx: 'auto', 
        p: 3,
        bgcolor: 'background.paper',
        borderRadius: 2,
        boxShadow: 1
      }}
    >
      <Typography variant="h5" gutterBottom>
        Create New Booking
      </Typography>
      
      <form onSubmit={onSaveBooking}>
        <Stack spacing={3}>
          <TextField
            required
            label="Title"
            value={formData.title}
            onChange={onPropertyChange('title')}
            error={!!errors.title}
            helperText={errors.title}
            disabled={loading}
            inputRef={titleRef}
          />

          <FormControl required error={!!errors.roomId}>
            <InputLabel>Room</InputLabel>
            <Select
              value={formData.roomId}
              label="Room"
              onChange={onPropertyChange('roomId')}
              disabled={loading}
            >
              <MenuItem value="">
                <em>Select a room</em>
              </MenuItem>
              {rooms.map((room) => (
                <MenuItem key={room.id} value={room.id}>
                  {room.name}
                </MenuItem>
              ))}
            </Select>
            {errors.roomId && <Typography color="error" variant="caption">{errors.roomId}</Typography>}
          </FormControl>

          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <Stack spacing={2}>
              <DateTimePicker
                label="Start Time"
                value={formData.start}
                onChange={onPropertyChange('start')}
                disabled={loading}
                slotProps={{
                  textField: {
                    required: true,
                    error: !!errors.start,
                    helperText: errors.start
                  }
                }}
              />
              <DateTimePicker
                label="End Time"
                value={formData.end}
                onChange={onPropertyChange('end')}
                disabled={loading}
                slotProps={{
                  textField: {
                    required: true,
                    error: !!errors.end,
                    helperText: errors.end
                  }
                }}
              />
            </Stack>
          </LocalizationProvider>

          <TextField
            label="Description"
            value={formData.description}
            onChange={onPropertyChange('description')}
            multiline
            rows={4}
            disabled={loading}
          />

          <Stack direction="row" spacing={2} justifyContent="flex-end">
            <Button
              variant="outlined"
              startIcon={<CancelIcon />}
              onClick={() => navigate(-1)}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              variant="contained"
              startIcon={<SaveIcon />}
              disabled={loading}
            >
              {loading ? 'Saving...' : 'Save'}
            </Button>
          </Stack>
        </Stack>
      </form>
    </Box>
  );
};

export default CreateBooking;